﻿using System.Collections.Generic;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public abstract class UIPagedPanelBase : UIPanelBase
{
    [SerializeField]
    private ToggleGroup m_ToggleGroup;
    [SerializeField]
    private Transform m_PageRoot;

    private List<Toggle> m_Toggles = new List<Toggle>();
    private List<UIPageBase> m_Pages = new List<UIPageBase>();

    public UIPageBase currentPage => m_Pages.Find(p => p.toggle.isOn);

    public override void OnInit()
    {
        for (int i = 0; i < m_PageRoot.childCount; i++)
        {
            var page = m_PageRoot.GetChild(i).GetComponent<UIPageBase>();
            if (page == null)
                continue;
            m_Pages.Add(page);
            page.gameObject.SetActive(true);
            page.OnInit();
        }
        m_ToggleGroup.transform.GetComponentsInChildren(true, m_Toggles);
        var index = -1;
        for (int i = 0; i < m_ToggleGroup.transform.childCount; i++)
        {
            var toggle = m_ToggleGroup.transform.GetChild(i).GetComponent<Toggle>();
            if (toggle == null)
                continue;
            index++;
            m_Toggles.Add(toggle);
            var page = m_Pages[index];
            toggle.isOn = false;
            toggle.group = m_ToggleGroup;
            toggle.OnValueChangedAsObservable().DistinctUntilChanged().Subscribe(isOn =>
            {
                if (isOn)
                {
                    page.gameObject.SetActive(true);
                    page.OnShow();
                }
                else
                {
                    page.gameObject.SetActive(false);
                    page.OnHide();
                }
            }).AddTo(this);
            page.index = index;
            page.toggle = toggle;
            page.panel = this;
        }
        m_Toggles[0].isOn = true;
    }

    public override void OnShow()
    {
        currentPage.OnShow();
    }

    public override void OnHide()
    {
        currentPage.OnHide();
    }

    public virtual void Refresh()
    {
        currentPage.Refresh();
    }

    public T FindPage<T>() where T : UIPageBase
    {
        return m_Pages.Find(p => p is T) as T;
    }
}